package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonSubmitDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.view.PopupWindowCutPic;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class SelectClassPicActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {

    public static final int SELECT_CLASS_PIC_CODE = 10006;

    @Bind(R.id.img1)
    ImageView img1;
    @Bind(R.id.img2)
    ImageView img2;
    @Bind(R.id.img3)
    ImageView img3;
    @Bind(R.id.img4)
    ImageView img4;
    @Bind(R.id.img5)
    ImageView img5;
    @Bind(R.id.img6)
    ImageView img6;
    @Bind(R.id.rootView)
    LinearLayout rootView;
    @Bind(R.id.class_pic)
    SimpleDraweeView classPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_class_pic, Status.STATUS);
        ButterKnife.bind(this);
        initToolbar("班级图标");
    }

    PopupWindowCutPic popupWindowCutPic;

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    String urlPath;

    @Override
    public void takeSuccess(TResult result) {

        urlPath = "file://" + result.getImage().getOriginalPath();

        if (!TextUtils.isEmpty(urlPath)) {
            classPic.setImageURI("file://" + urlPath);
//            finishActivity(urlPath);
            uploadClassHeaderImage(result.getImage().getOriginalPath());
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        urlPath = "";
    }

    @Override
    public void takeCancel() {
        urlPath = "";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    public void saveBitmapFile(Bitmap bitmap) {

        if (bitmap == null) {
            LogUtil.MyLog("adfaf", "123123");
            return;
        }


        File fileDir = new File(FileUtils.getPicPath());
        if (!fileDir.exists()) {
            if (!fileDir.mkdirs()) {
                Toast.makeText(this, "创建文件夹失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        String filePath = FileUtils.getPicPath() + System.currentTimeMillis() + ".jpg";

        File file = new File(filePath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            uploadClassHeaderImage(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private CropOptions getCropOptions() {
        int height = 400;
        int width = 400;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    @OnClick({R.id.img1, R.id.img2, R.id.img3, R.id.img4, R.id.img5, R.id.img6})
    public void onViewClicked(View view) {
        Bitmap bitmap = null;
        switch (view.getId()) {
            case R.id.img1:

                urlPath = "res://com.fancy.learncenter/" + R.mipmap.default_class_1_icon;
                bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.default_class_1_icon);
                saveBitmapFile(bitmap);
                break;
            case R.id.img2:

                urlPath = "res://com.fancy.learncenter/" + R.mipmap.default_class_2_icon;
                bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.default_class_2_icon);
                saveBitmapFile(bitmap);
                break;
            case R.id.img3:

                urlPath = "res://com.fancy.learncenter/" + R.mipmap.default_class_3_icon;
                bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.default_class_3_icon);
                saveBitmapFile(bitmap);
                break;
            case R.id.img4:

                urlPath = "res://com.fancy.learncenter/" + R.mipmap.default_class_4_icon;
                bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.default_class_4_icon);
                saveBitmapFile(bitmap);
                break;
            case R.id.img5:

                urlPath = "res://com.fancy.learncenter/" + R.mipmap.default_class_5_icon;
                bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.default_class_5_icon);
                saveBitmapFile(bitmap);
                break;
            case R.id.img6:

                if (popupWindowCutPic == null) {

                    popupWindowCutPic = new PopupWindowCutPic(rootView);

                    popupWindowCutPic.setOnClickListener(new PopupWindowCutPic.CutPicCallBack() {
                        @Override
                        public void choose() {
                            File file = new File(Environment.getExternalStorageDirectory(), Constant.HEADER_CUT_PATH + System.currentTimeMillis() + ".jpg");
                            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                            Uri imageUri = Uri.fromFile(file);
                            getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());

                            popupWindowCutPic.dismiss();
                        }

                        @Override
                        public void cancel() {
                            popupWindowCutPic.dismiss();
                        }

                        @Override
                        public void camera() {
                            File file2 = new File(Environment.getExternalStorageDirectory(), Constant.HEADER_CUT_PATH + System.currentTimeMillis() + ".jpg");
                            if (!file2.getParentFile().exists()) file2.getParentFile().mkdirs();
                            Uri imageUri2 = Uri.fromFile(file2);
                            getTakePhoto().onPickFromCaptureWithCrop(imageUri2, getCropOptions());

                            popupWindowCutPic.dismiss();
                        }

                        @Override
                        public void see() {

                        }
                    });
                }

                popupWindowCutPic.isShow();
                break;
        }
    }

    private void finishActivity(String urlPath, String picId) {
        Intent intent = getIntent();
        intent.putExtra(CartoonCreatClassActivity.NAME_KEY, urlPath);
        intent.putExtra(CartoonCreatClassActivity.SCHOOL_ID_KEY, picId);
        setResult(SELECT_CLASS_PIC_CODE, intent);
        finish();
    }

    String picId = "";

    private void uploadClassHeaderImage(String urlPaths) {

        HttpMehtod.getInstance().uploadClassHeaderImage(urlPaths, new CustomNetSubscriber(this, true) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                BaseBean<CartoonSubmitDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonSubmitDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonSubmitDataBean>() {
                    @Override
                    public void success(CartoonSubmitDataBean dataBean) {

                        if (dataBean != null && !TextUtils.isEmpty(dataBean.getResourceId())) {
                            finishActivity(urlPath, dataBean.getResourceId());
                        }

                    }

                    @Override
                    public void fail(String errorCode) {
                        ToastUtil.show("上传失败");
                        finishActivity(urlPath, "1");
                    }


                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);


                finishActivity(urlPath, "1");

            }
        });
    }

//    public void copyFilesFassets(Context context, String oldPath, String newPath) {
//        try {
//            String fileNames[] = context.getAssets().list(oldPath);//获取assets目录下的所有文件及目录名
//            if (fileNames.length > 0) {//如果是目录
//                File file = new File(newPath);
//                file.mkdirs();//如果文件夹不存在，则递归
//                for (String fileName : fileNames) {
//                    copyFilesFassets(context, oldPath + "/" + fileName, newPath + "/" + fileName);
//                }
//            } else {//如果是文件
//                InputStream is = context.getAssets().open(oldPath);
//                FileOutputStream fos = new FileOutputStream(new File(newPath));
//                byte[] buffer = new byte[1024];
//                int byteCount = 0;
//                while ((byteCount = is.read(buffer)) != -1) {//循环从输入流读取 buffer字节
//                    fos.write(buffer, 0, byteCount);//将读取的输入流写入到输出流
//                }
//                fos.flush();//刷新缓冲区
//                is.close();
//                fos.close();
//            }
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            //如果捕捉到错误则通知UI线程
//        }
//    }

}
